package org.scau.studentevaluation.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.scau.studentevaluation.entity.dos.RulesDO;
import org.scau.studentevaluation.entity.query.RuleQuery;
import org.scau.studentevaluation.entity.vos.RuleVO;
import org.scau.studentevaluation.exception.FieldNullException;
import org.scau.studentevaluation.util.BeanConvertUtils;
import org.scau.studentevaluation.util.DateUtil;
import org.scau.studentevaluation.util.FieldCheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RulesServieceImpl implements RulesServiece {
    @Autowired
    private ImportMapperService importMapperService;
    @Autowired
    private FieldCheckUtil fieldCheckUtil;

    @Override
    public List<RuleVO> getRules(String college) {
        // 获取学年
        int year = DateUtil.YEAR();
        // 查询数据
        QueryWrapper<RulesDO> rulesDOQueryWrapper = new QueryWrapper<>();
        rulesDOQueryWrapper.eq("year",year)
                .eq("college",college);
        // 对象转换
        List<RulesDO> rulesDOS = importMapperService.rulesMapper.selectList(rulesDOQueryWrapper);
        log.debug("查询结果{}",rulesDOS);
        List<RuleVO> ruleVOS = BeanConvertUtils.BOs2VOs(rulesDOS, RuleVO.class);

        return ruleVOS;
    }

    @Override
    public String getDetailRule(RuleQuery query) throws FieldNullException {
        // 空参数检查
        fieldCheckUtil.throwNULLServiceException(query);
        // 查询
        String rulesDO = importMapperService.rulesMapper.detailRule(query);

        return rulesDO;
    }

    @Override
    @Transactional
    public int uploadRules(List<RulesDO> rules) {
        // 若未传年份参数，默认是今年
        rules.forEach(x->x.setYear(x.getYear() == null ? DateUtil.YEAR() : x.getYear()));

        // 看看都有谁要被覆盖了
        Set<RulesDO.CollegeAndYear> collegeAndYears = rules.stream()
                .map(RulesDO::getCollegeAndYear)
                .collect(Collectors.toSet());
        // 覆盖第一步：删除
        for (RulesDO.CollegeAndYear collegeAndYear : collegeAndYears) {
            QueryWrapper<RulesDO> rulesDOQueryWrapper = new QueryWrapper<>();
            rulesDOQueryWrapper.eq("college",collegeAndYear.getCollege())
                    .eq("year",collegeAndYear.getYear());
            importMapperService.rulesMapper.delete(rulesDOQueryWrapper);
        }
        // 覆盖第二步：强势插入
        rules.forEach(x->importMapperService.rulesMapper.insert(x));

        return rules.size();
    }

}
